﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region Using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
#endregion

namespace NetBay.Core.Silverlight.Extensions
{
    public class EnumEx
    {
        public static IEnumerable<T> GetEnumValues<T>()
        {
            return GetFieldsEnums<T>().Select(item => (T)item.GetValue(null));
        }

        public static IEnumerable<string> GetStringEnumValues<T>()
        {
            return GetFieldsEnums<T>().Select(item => item.GetValue(null).ToString());
        }

        public static IEnumerable<string> GetDescriptionEnumValues<T>()
        {
            return GetFieldsEnums<T>().Select(DescriptionAttribute);
        }

        public static IEnumerable<int> GetIntEnumValues<T>()
        {
            return GetFieldsEnums<T>().Select(item => (int)item.GetValue(null));
        }

        public static IEnumerable<Tuple<int, string>> GetIntStringEnumValues<T>()
        {
            return GetFieldsEnums<T>().Select(item =>
            {
                Object l_oObject = item.GetValue(null);
                return Tuple.Create((int)l_oObject, l_oObject.ToString());
            }
                );
        }

        public static IEnumerable<Tuple<int, string>> GetIntDescriptionEnumValues<T>()
        {
            return GetFieldsEnums<T>().Select(item => Tuple.Create((int)item.GetValue(null), DescriptionAttribute(item)));
        }

        #region Privates fonctions
        private static IEnumerable<FieldInfo> GetFieldsEnums<T>()
        {
            Type type = typeof(T);

            if (!type.IsEnum)
            {
                throw new Exception(type.FullName + " is not an enum.");
            }

            IEnumerable<FieldInfo> ret = type.GetFields(BindingFlags.Public | BindingFlags.Static);

            return ret;
        }
        private static string DescriptionAttribute(FieldInfo fi)
        {
            DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
            string l_szRet = da != null ? da.Description : fi.GetValue(null).ToString();

            return l_szRet;
        }
        #endregion
    }
}
